package marvin.webapp.audio.subscription;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import marvin.webapp.audio.util.PushNotifier;

public class SubscriptionServer extends Thread {

	private int port; 
	private boolean run = false;
	private ServerSocket welcomeSocket;
	private static List<ClientHandler> clients;
	
	public SubscriptionServer(int port){
		this.port = port;
		if(clients == null)
			clients = new ArrayList<ClientHandler>();
	}
	
	public void run(){
		try {
			welcomeSocket = new ServerSocket(port);
			run = true;
			System.out.println("Server started");
			int rtpBasePort = 20000;
			while(run){
				Socket connectionSocket = welcomeSocket.accept();
				
				System.out.println("Connected: "+connectionSocket.getRemoteSocketAddress());
				ClientHandler client = new ClientHandler(connectionSocket, this, rtpBasePort);
				client.start();
				
				clients.add(client);
				rtpBasePort ++;
				PushNotifier.sendNotification("Client connection", "New client connected");
			}
			System.out.println("Server stopped");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void removeClient(ClientHandler c){
		clients.remove(c);
		PushNotifier.sendNotification("Client connection", "Client disconnected");
	}
	
	public void stopServer(){
		run = false;
		this.notify();
	}

	public List<ClientHandler> getClients() {
		return clients;
	}
}
